//
//  InfoViewController.m
//  QuickCure1
//
//  Created by 胡晨晨 on 16/11/2.
//  Copyright © 2016年 maoge. All rights reserved.
//

#import "InfoViewController.h"
#import "InfoHeadView.h"
#import "Users.h"
#import "InfoTableViewCell.h"
#import "Province.h"
static NSString *cellId = @"cellId";

@interface InfoViewController ()<UITableViewDelegate,UITableViewDataSource,UIPickerViewDelegate,UIPickerViewDataSource>

//省市模型
@property(nonatomic,strong)NSArray<Province*>* provinceModelList;



@property(nonatomic,weak)UITableView *tableView;


@property(nonatomic,weak)UIPickerView *pickerView;

@end

@implementation InfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self loadData];
    
    
    [self setupUI];
    
}

- (NSArray<Province *> *)provinceModelList{
    if (!_provinceModelList) {
        _provinceModelList = [NSArray array];
    }
    return _provinceModelList;
}


/**
 加载省市数据
 */
-(void)loadData{
    
    NSString *path = [[NSBundle mainBundle]pathForResource:@"province.plist" ofType:nil];
    
    NSArray *array = [NSArray arrayWithContentsOfFile:path];
    
    self.provinceModelList = [Province citiesWithArray:array];
    
    
}


#pragma mark-
#pragma mark-搭建界面
- (void)setupUI
{
    self.title = @"个人信息";
    
    
    UITableView *tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT) style:UITableViewStylePlain];

    [self.view addSubview:tableView];
    
    _tableView = tableView;
    
    //创建表头
    InfoHeadView *infoView = [InfoHeadView infoHead];
    
    infoView.userModel = self.userModel;
    
    tableView.tableHeaderView = infoView;
    
    
    tableView.delegate = self;
    tableView.dataSource = self;
    
    [tableView registerClass:[InfoTableViewCell class] forCellReuseIdentifier:cellId];
    
    
    
    //取消tableView多余的分割线
    UIView *view = [UIView new];
    
    view.backgroundColor = [UIColor clearColor];
    
    [tableView setTableFooterView:view];
    
    
}

#pragma mark-
#pragma mark-tableView代理方法
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return 3;
}

- (UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    InfoTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId forIndexPath:indexPath];
    cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    
     switch (indexPath.row) {
        case 0:
        {
            
            cell.textLabel.text = @"身高";
            if ([self.userModel.height stringValue]) {
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ cm",[self.userModel.height stringValue]];
            }else{
                cell.detailTextLabel.text = @" cm";
            }

        }
            break;
        case 1:
        {
            cell.textLabel.text = @"体重";
            if ([self.userModel.weight stringValue]) {
                cell.detailTextLabel.text = [NSString stringWithFormat:@"%@ kg",[self.userModel.weight stringValue]];
            }else{
                cell.detailTextLabel.text = @" kg";
            }

        }
            break;
        case 2:
        {
            cell.textLabel.text = @"省份";
            cell.detailTextLabel.text = self.userModel.address;
        }
            break;
            
        default:
            break;
    }
    
    
    return cell;
    
    
}



- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    switch (indexPath.row) {
        case 0:
        {
            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"请输入身高" message:@"cm" delegate:self cancelButtonTitle:@"修改" otherButtonTitles:@"取消",nil];
            //区分两个alert
            dialog.tag = 0;
            
            [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];
            [[dialog textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
            [dialog show];
        }
            break;
        case 1:
        {
            UIAlertView *dialog = [[UIAlertView alloc] initWithTitle:@"请输入体重" message:@"kg" delegate:self cancelButtonTitle:@"修改" otherButtonTitles:@"取消",nil];
            //区分两个alert
            dialog.tag = 1;
            
            [dialog setAlertViewStyle:UIAlertViewStylePlainTextInput];
            [[dialog textFieldAtIndex:0] setKeyboardType:UIKeyboardTypeNumberPad];
            [dialog show];
            
        }
            break;
        case 2:
        {
            
            if (!self.pickerView) {
                //创建省市选择器
                [self setupPickerView];
            }
        }
            break;
        default:
            break;
    }
    
    
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex NS_DEPRECATED_IOS(2_0, 9_0){
   // self.userModel.height = [alertView textFieldAtIndex:0].text ;
    
    
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *numTemp = [numberFormatter numberFromString:[alertView textFieldAtIndex:0].text];
    
    if(alertView.tag == 0){
        self.userModel.height = numTemp;
    }else{
        self.userModel.weight = numTemp;
    }
    [self.tableView reloadData];
    
}


#pragma mark-
#pragma mark-创建省市选择器
- (void)setupPickerView
{
    UIPickerView *pickerView = [[UIPickerView alloc]init];
    
    _pickerView = pickerView;
    
    [self.view addSubview:pickerView];
    
    [pickerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(self.view);
        make.height.equalTo(@(160));
    }];
    //设置代理
    pickerView.delegate = self;
    pickerView.dataSource = self;
    
    
    
    //添加toolbar
    UIToolbar *toolBar = [[UIToolbar alloc]init];
    
    [self.view addSubview:toolBar];
    
    [toolBar mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.equalTo(self.view);
        make.bottom.equalTo(pickerView.mas_top);
        make.height.equalTo(@44);
    }];
    
    
    UIBarButtonItem *completeBtn = [[UIBarButtonItem alloc]initWithTitle:@"完成" style:UIBarButtonItemStyleDone target:self action:@selector(complete)];
    
    UIBarButtonItem *space = [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
    
        UIBarButtonItem *cancle = [[UIBarButtonItem alloc]initWithTitle:@"取消" style:UIBarButtonItemStyleDone target:self action:@selector(cancle)];
    
    toolBar.items = @[cancle,space,space,completeBtn];
    
}


//完成省份修改
- (void)complete{
    NSInteger rowProvince = [self.pickerView selectedRowInComponent:0];
    NSInteger rowCity = [self.pickerView selectedRowInComponent:1];
    NSString *province = self.provinceModelList[rowProvince].name;
    NSString *city = self.provinceModelList[rowProvince].cities[rowCity];
    
    NSString *newAdd = [NSString string];
    if ([province isEqualToString:city]) {
        newAdd = [NSString stringWithFormat:@"%@市",province];
    }else{
        newAdd = [NSString stringWithFormat:@"%@省 %@市",province,city];
    }
    
    self.userModel.address = newAdd;
    
    [self.tableView reloadData];
    
    //移除
    [_pickerView removeFromSuperview];
    
}

//取消修改
- (void)cancle{
    [_pickerView removeFromSuperview];
}



#pragma mark-
#pragma mark-pickView代理方法
// returns the number of 'columns' to display.
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 2;
}

// returns the # of rows in each component..
- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    if (component == 0) {
        return self.provinceModelList.count;
    }
    else{
        NSInteger rowProvince = [pickerView selectedRowInComponent:0];
        return self.provinceModelList[rowProvince].cities.count;
        
    }
}

//每列宽度
- (CGFloat)pickerView:(UIPickerView *)pickerView widthForComponent:(NSInteger)component
{
    return 100;
}

- (CGFloat)pickerView:(UIPickerView *)pickerView rowHeightForComponent:(NSInteger)component{
    return 28;
}
/*
//返回内容
- (NSString*)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        return self.provinceModelList[row].name;
    }
    else{
        //每个省份的市数目
        NSInteger rowProvince = [pickerView selectedRowInComponent:0];
        return self.provinceModelList[rowProvince].cities[row];
        
    }
    
}
*/

- (NSAttributedString*)pickerView:(UIPickerView *)pickerView attributedTitleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        Province *province = self.provinceModelList[row];
        NSDictionary *dict = @{NSFontAttributeName:FONT(28),NSForegroundColorAttributeName:[UIColor blackColor]};
        NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]initWithString:province.name attributes:dict];
        
        return attr;
    }
    else{
        //每个省份的市数目
        NSInteger rowProvince = [pickerView selectedRowInComponent:0];
        Province *province = self.provinceModelList[rowProvince];
        if (province.cities.count > row) {
            NSDictionary *dict = @{NSFontAttributeName:FONT(28),NSForegroundColorAttributeName:[UIColor blackColor]};
            NSMutableAttributedString *attr = [[NSMutableAttributedString alloc]initWithString:province.cities[row] attributes:dict];
            
            return attr;
        }
        else{
            return [[NSMutableAttributedString alloc]initWithString:@"" attributes:nil];
        }
        
        
    }
}


- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component
{
    if (component == 0) {
        //左边滑动时立即刷新右边
        [pickerView reloadComponent:1];
    }
    
}


#pragma mark-
#pragma mark-视图将要消失时,归档
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    //路径
    NSString *filePath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES).lastObject stringByAppendingPathComponent:@"user.plist"];
    //归档
    [NSKeyedArchiver archiveRootObject:self.userModel toFile:filePath];
    
    NSLog(@"%@",NSHomeDirectory());
    
    //在左栏控制器解档
    
}




/*- (UIView*)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
